package ws.very.util

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec


package object security {
  import ws.very.util.lang.Implicits2._

  object MD5 {
    def md5handle = java.security.MessageDigest.getInstance("MD5")
    private val hexDigits = Array[Char]('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
    def apply(str: S):S = {
      this.apply(str.getBytes)
    }
    def apply(bytes:Array[Byte]):S = {
      val encrypt = md5handle.digest(bytes)
      val b = new StringBuilder(32)
      for (i <- 0.to(15)) {
        b.append(hexDigits(encrypt(i) >>> 4 & 0xf)).append(hexDigits(encrypt(i) & 0xf))
      }
      b.mkString
    }

  }
  object SHA{
    val SHA_1 = "SHA-1"
    val SHA_256 = "SHA-256"
    def apply(str:S,strType:S):S = {
      val messageDigest = MessageDigest.getInstance(strType)
      messageDigest.update(str.getBytes)
      val byteBuffer = messageDigest.digest()
      val strHexString = new StringBuffer()
      for{
        byte<-byteBuffer
      }{
        val hex = Integer.toHexString(0xff & byte)
        if (hex.length() == 1){
          strHexString.append('0')
        }
        strHexString.append(hex)
      }
      strHexString.toString
    }
  }

  object HmacSHA256{
    def hex(key:S, str:S):S = {
      val sha256HMAC = Mac.getInstance("HmacSHA256")
      val secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256")
      sha256HMAC.init(secretKey)
      import javax.xml.bind.DatatypeConverter
      DatatypeConverter.printHexBinary(sha256HMAC.doFinal(str.getBytes("UTF-8")))
    }

    def base64(key:S, str:S):S ={
      val sha256HMAC = Mac.getInstance("HmacSHA256")
      val secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256")
      sha256HMAC.init(secretKey)
      import javax.xml.bind.DatatypeConverter
      DatatypeConverter.printBase64Binary(sha256HMAC.doFinal(str.getBytes("UTF-8")))
    }
  }
}